package cn.doctorpda.conference.utils;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import cn.doctorpda.conference.event.CollectShareJsInfo;
import cn.doctorpda.conference.event.CollectWebToAppInfo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by huangjinlong on 2016/5/24.
 */
public class JsInterface {
    private Context mContext;
    public JsInterface(Context context) {
        this.mContext = context;
    }

    /**
     * 分享的js交互
     *
     * @param json
     * @throws JSONException
     */
    @JavascriptInterface
    public void app_share(String json) throws JSONException {
        JSONObject jsonObject = new JSONObject(json);
        String text = jsonObject.getString("description");
        String title = jsonObject.getString("title");
        String url = jsonObject.getString("url");
        String thumb = jsonObject.getString("thumb");
        String to = jsonObject.getString("to");
        String platformToShare;
        if (to.equals("weixin")) {
            platformToShare = Wechat.NAME;
        } else if (to.equals("qq")) {
            platformToShare = QQ.NAME;
        } else {
            platformToShare = WechatMoments.NAME;
        }
        ShareUtils.showShare(mContext, platformToShare, false, title, text, thumb, url);
    }

    @JavascriptInterface
    public void to_app_data(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        CollectShareJsInfo info_get = new CollectShareJsInfo();
        L.d("to_app_data"+json.toString());
        if (!TextUtils.isEmpty(json)) {

            info_get.setIsCollected(object.getString("isCollected"));
            info_get.setCollectId(object.getString("collect_id"));
            info_get.setType(object.getString("type"));
            info_get.setTitle(object.getString("title"));
            info_get.setDescription(object.getString("description"));
            info_get.setUrl(object.getString("url"));
            info_get.setThumb(object.getString("thumb"));
            if(object.has("comments"))
            info_get.setComments(object.getString("comments"));
        }
        EventBus.getDefault().post(info_get);
    }


    @JavascriptInterface
    public void to_app_action(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        CollectWebToAppInfo info = new CollectWebToAppInfo();
        info.setType(object.getString("type"));
        info.setData(object.getString("data"));
        EventBus.getDefault().post(info);
    }


}
